import React from 'react';
// import { Button } from 'antd';
// import { AuthDiv } from 'components';
import { Terminal } from 'xterm';
import { FitAddon } from 'xterm-addon-fit';
// import { http, X_TOKEN } from 'libs';
import 'xterm/css/xterm.css';
import styles from './style.less';

import { getPageQuery } from '@/utils/utils';
import { getMachine } from "@/services/machine"


class WebSSH extends React.Component {
    term: Terminal
    socket: any
    container: any
    id: number
    constructor(props: any) {
        super(props);
        this.id = props.match.params.id;
        this.socket = null;
        this.term = new Terminal();
        this.container = null;
        // this.input = null;
        this.state = {
            visible: false,
            uploading: false,
            managerDisabled: true,
            host: {

            },
            percent: 0,
            cmd: ''
        }
    }

    componentDidMount() {
        const query = getPageQuery()
        const ID: any = query.id || 0
        this.getMachineInfo();
        const fitPlugin = new FitAddon();
        this.term.loadAddon(fitPlugin);
        const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
        this.socket = new WebSocket(`${protocol}//${window.location.host}/ws/ssh?id=${ID}&x-token=xxxffffdddss`);
        // this.socket = new WebSocket(`ws://127.0.0.1:1323/ws/ssh?id=${ID}`);
        this.socket.onmessage = (e: any) => {
            this._read_as_text(e.data)
        };
        this.socket.onopen = () => {
            this.term.open(this.container);
            this.term.focus();
            fitPlugin.fit();
        };
        this.socket.onclose = (e: any) => {
            if (e.code === 3333) {
                window.location.href = "about:blank";
                window.close()
            } else {
                setTimeout(() => this.term.write('\r\nConnection is closed.\r\n'), 200)
            }
        };
        this.term.onData(key => {
            let data = {
                type: 'cmd',
                cmd: key,
                cols: 0,
                rows: 0
            }
            data.cmd = window.btoa(key);
            this.socket.send(JSON.stringify(data))
        });
        this.term.onResize(({ cols, rows }) => {
            const param = {
                type: 'resize',
                cmd: '',
                cols,
                rows
            }
            this.socket.send(JSON.stringify(param))
        });
        window.onresize = () => fitPlugin.fit()
    }

    _read_as_text = (data: any) => {
        const reader = new window.FileReader();
        reader.onload = () => this.term.write(reader.result);
        reader.readAsText(data, 'utf-8')
    };

    handleShow = () => {
        this.setState({ visible: !this.state.visible })
    };

    getMachineInfo = () => {
        const query = getPageQuery()
        const ID: any = query.id || 0

        if (ID > 0) {
            getMachine({ id: ID }).then(res => {
                if (res.code == 0 && res.results.length > 0) {
                    const row = res.results[0]
                    const host = {
                        name: row.use,
                        username: row.username,
                        hostname: row.ip,
                        port: row.port
                    }

                    this.setState({ host: host })
                    document.title = `${host.name} | ${host.hostname}`;
                }
            })
        }
    }

    render() {
        const { host } = this.state;
        return (
            <div className={styles.container}>
                <div className={styles.header}>
                    <div>{host.name} | {host.username}@{host.hostname}:{host.port}</div>
                    {/* <AuthDiv auth="host.console.manager">
            <Button disabled={managerDisabled} type="primary" icon="folder-open"
                    onClick={this.handleShow}>文件管理器</Button>
          </AuthDiv> */}
                </div>
                <div className={styles.terminal}>
                    <div ref={ref => this.container = ref} />
                </div>
                {/* <FileManager id={this.id} visible={visible} onClose={this.handleShow}/> */}
            </div>
        )
    }
}

export default WebSSH